package com.it.aspect;

import com.it.annotation.ClearCache;
import com.it.component.AuthorizationCache;
import lombok.RequiredArgsConstructor;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * @author TBH
 * @date 2025-05-02 08:42:31
 * @desc
 */
@Aspect
@Component
@RequiredArgsConstructor
public class ClearCacheAspect {

    private final AuthorizationCache authorizationCache;

    @AfterReturning(pointcut = "@annotation(clearCache)", returning = "result")
    public void afterReturningWithAnnotation(ClearCache clearCache, Object result) {
        ClearCache.CacheType[] cacheTypes = clearCache.cacheNames();
        Objects.requireNonNull(cacheTypes);
        for (ClearCache.CacheType cacheType : cacheTypes) {
            if (Objects.equals(cacheType, ClearCache.CacheType.ROLES)) {
                authorizationCache.clearRoles();
            }
            if (Objects.equals(cacheType, ClearCache.CacheType.PERMISSIONS)) {
                authorizationCache.clearPermissions();
            }
        }
        if (clearCache.clearKeys()) {
            String[] keys = clearCache.keys();
            authorizationCache.clearKeys(keys);
        }
    }
}